package cn.com.dashihui.web.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.kit.ListKit;
import cn.com.dashihui.web.common.ServiceOrderCode;
import cn.com.dashihui.web.dao.ServiceOrder;

public class ServiceOrderService {

	/**
	 * 分页查找订单信息
	 * @param orderNum 订单编号
	 * @param beginDate 下单时间
	 * @param endDate 成交时间
	 * @param state 订单状态，0：全部，1：待付款，2：待派单，3：待确认，4：已确认，6：被催单
	 * @param address 买家地址
	 * @param tel 买家电话
	 * @param payType 支付方式
	 */
	public Page<Record> findByPage(int pageNum,int pageSize,int storeid,String orderNum,String beginDate,String endDate,int state,String address,String tel,int payType){
		StringBuffer sBuffer = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		sBuffer.append("FROM t_bus_service_order A WHERE A.storeid=?");
		params.add(storeid);
		if(!StrKit.isBlank(orderNum)){
			sBuffer.append(" AND A.orderNum=?");
			params.add(orderNum);
		}
		if(!StrKit.isBlank(beginDate)&&!StrKit.isBlank(endDate)){
			sBuffer.append(" AND A.startDate BETWEEN ? AND ?");
			params.add(beginDate);
			params.add(endDate);
		}else if(!StrKit.isBlank(beginDate)&&StrKit.isBlank(endDate)){
			sBuffer.append(" AND DATE_FORMAT(A.startDate,'%Y-%m-%d')>=?");
			params.add(beginDate);
		}else if(StrKit.isBlank(beginDate)&&!StrKit.isBlank(endDate)){
			sBuffer.append(" AND DATE_FORMAT(A.startDate,'%Y-%m-%d')<=?");
			params.add(endDate);
		}
		switch (state) {
			case 1://待付款（“在线支付”、“未支付”、“正常”）
				sBuffer.append(" AND payType=? AND payState=? AND orderState=?");
				params.add(ServiceOrderCode.OrderPayType.ON_LINE);
				params.add(ServiceOrderCode.OrderPayState.NO_PAY);
				params.add(ServiceOrderCode.OrderState.NORMAL);
				break;
			case 2://待派单（1：“在线支付”、“已支付”、“未派单”、“正常”，2：“服务后付款”、“未派单”、“正常”）
				sBuffer.append(" AND ((payType=? AND payState=?) OR payType=?) AND deliverState=? AND orderState=?");
				params.add(ServiceOrderCode.OrderPayType.ON_LINE);
				params.add(ServiceOrderCode.OrderPayState.HAD_PAY);
				params.add(ServiceOrderCode.OrderPayType.AFTER_SERVICE);
				params.add(ServiceOrderCode.OrderDispatchState.NO_DISPATCH);
				params.add(ServiceOrderCode.OrderState.NORMAL);
				break;
			case 3://待确认（1：“在线支付”、“已支付”、“已派单”、“正常”，2：“服务后付款”、“已派单”、“正常”）
				sBuffer.append(" AND ((payType=? AND payState=?) OR payType=?) AND deliverState=? AND orderState=?");
				params.add(ServiceOrderCode.OrderPayType.ON_LINE);
				params.add(ServiceOrderCode.OrderPayState.HAD_PAY);
				params.add(ServiceOrderCode.OrderPayType.AFTER_SERVICE);
				params.add(ServiceOrderCode.OrderDispatchState.HAD_DISPATCH);
				params.add(ServiceOrderCode.OrderState.NORMAL);
				break;
			case 4://已确认（1：“在线支付”、“已支付”、“已派单”、“已确认”，2：“服务后付款”、“已派单”、“已确认”）
				sBuffer.append(" AND ((payType=? AND payState=?) OR payType=?) AND deliverState=? AND orderState=?");
				params.add(ServiceOrderCode.OrderPayType.ON_LINE);
				params.add(ServiceOrderCode.OrderPayState.HAD_PAY);
				params.add(ServiceOrderCode.OrderPayType.AFTER_SERVICE);
				params.add(ServiceOrderCode.OrderDispatchState.HAD_DISPATCH);
				params.add(ServiceOrderCode.OrderState.FINISH);
				break;
			default:
				//默认不查询取消、过期、删除的订单
				sBuffer.append(" AND orderState!=? AND orderState!=? AND orderState!=?");
				params.add(ServiceOrderCode.OrderState.CANCEL);
				params.add(ServiceOrderCode.OrderState.EXPIRE);
				params.add(ServiceOrderCode.OrderState.DELETE);
				break;
		}
		if(!StrKit.isBlank(address)){
			sBuffer.append(" AND address LIKE ?");
			params.add("%"+address+"%");
		}
		if(!StrKit.isBlank(tel)){
			sBuffer.append(" AND tel=?");
			params.add(tel);
		}
		if(payType!=0){
			sBuffer.append(" AND A.payType=?");
			params.add(payType);
		}
		
		sBuffer.append(" ORDER BY createDate DESC");
		//查询出符合条件的订单列表
		Page<Record> page = Db.paginate(pageNum,pageSize,"SELECT * ",sBuffer.toString(),params.toArray());
		if(page.getList()!=null&&page.getList().size()!=0){
			//将各订单对应的订单商品查出
			return new Page<Record>(findServiceByOrder(page.getList()), page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow());
		}
		return page;
	}
	
	/**
	 * 为指定订单列表，查找出相应的服务项清单并set给每个订单记录
	 * @param orderList
	 */
	private List<Record> findServiceByOrder(List<Record> orderList){
		//拼接SQL
		StringBuffer sBuffer = new StringBuffer("SELECT orderNum,shopid,shopName,shopThumb,serviceid,serviceTitle,amount FROM t_bus_service_order_list WHERE orderNum IN (");
		for(Record order : orderList){
			sBuffer.append("'").append(order.getStr("orderNum")).append("',");
		}
		sBuffer.replace(sBuffer.lastIndexOf(","), sBuffer.length(), ")");
		sBuffer.append(" ORDER BY orderNum");
		//整理结果
		List<Record> serviceList = Db.find(sBuffer.toString());
		if(serviceList!=null){
			//先将查出来的所有的订单服务项，按订单号归类
			Map<String,List<Record>> serviceMap = new HashMap<String,List<Record>>();
			for(Record service : serviceList){
				if(serviceMap.containsKey(service.getStr("orderNum"))){
					((List<Record>)serviceMap.get(service.getStr("orderNum"))).add(service);
				}else{
					serviceMap.put(service.getStr("orderNum"), new ListKit<Record>().add(service).getList());
				}
			}
			//遍历订单列表的同时，设置对应订单商品集
			for(Record order : orderList){
				order.set("serviceList", serviceMap.get(order.get("orderNum")));
			}
		}
		return orderList;
	}

	/**
	 * 根据订单号查询出订单
	 */
	public ServiceOrder getOrderByOrderNum(String orderNum){
		String sql = "SELECT * FROM t_bus_service_order WHERE orderNum=?";
		return ServiceOrder.me().findFirst(sql,orderNum);
	}

	/**
	 * 根据订单号查询出服务项清单
	 */
	public List<Record> getServiceListByOrderNum(String orderNum){
		String sql = "SELECT bsol.*,bss.name shopName,bss.tel shopTel FROM t_bus_service_order_list bsol LEFT JOIN t_bus_service_shop bss ON bsol.shopid=bss.id WHERE orderNum=?";
		return Db.find(sql, orderNum);
	}

	/**
	 * 根据订单号查询订单操作日志
	 */
	public List<Record> getLogListByOrderNum(String orderNum){
		String sql = "SELECT * FROM t_bus_service_order_log WHERE orderNum=? ORDER BY createDate";
		return Db.find(sql, orderNum);
	}

	/**
	 * 更新
	 */
	public boolean update(ServiceOrder order){
		//将Record的所有字段转化为一个Order对象后，提交更新
		return order.update();
	}
	
	/**
	 * 记录操作日志
	 */
	public void log(String orderNum, String user, String action, String content){
		Db.update("INSERT INTO t_bus_service_order_log(orderNum,user,action,content) VALUES(?,?,?,?)",orderNum,user,action,content);
	}
}
